package com.xywl.escort.view.certified

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bilibili.boxing.Boxing
import com.bilibili.boxing.model.config.BoxingConfig
import com.bilibili.boxing.model.config.BoxingCropOption
import com.bilibili.boxing.model.entity.impl.ImageMedia
import com.bilibili.boxing.utils.BoxingFileHelper
import com.bilibili.boxing_impl.ui.BoxingActivity
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.AddUserAutoInfoResp
import com.xywl.escort.bean.UserAutoInfoResp
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.CustomDialog
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_certified.*
import timber.log.Timber
import top.zibin.luban.Luban
import java.io.File
import java.util.*
import javax.inject.Inject
import kotlin.collections.HashMap

@Route(path = "/xy/certified")
class CertifiedActivity : BaseActivity(), CertifiedContract.View {
    private var isSelectPositive: Boolean = false
    private var isSelectNegative: Boolean = false
    private var mDialog: CustomDialog? = null
    private var mDisposable: CompositeDisposable? = null
    private val mFileList = HashMap<String, File>()
    @Inject
    lateinit var mPresenter: CertifiedContract.Presenter

    @Autowired
    @JvmField
    var dataBean: UserAutoInfoResp.DataBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_certified)
        ARouter.getInstance().inject(this)
        showBackButton()
        setTitleText("实名信息")

        mPresenter.takeView(this)
        dataBean?.let {
            initView(dataBean!!)
        }
        dataBean?.let {
            addListener(dataBean!!)
        }

        mDisposable = CompositeDisposable()
    }

    private fun initView(bean: UserAutoInfoResp.DataBean) {
        when (bean.status) {
            1 -> {
                btn_submit.text = "提交"
                image_approved.visibility = View.GONE
                enabled()
                btn_submit.isEnabled = true
            }
            2 -> {
                btn_submit.text = "审核中"
                image_approved.visibility = View.GONE
                banEnabled()
                btn_submit.isEnabled = false
                setImage(bean)
            }
            3 -> {
                btn_submit.text = "已认证"
                banEnabled()
                btn_submit.isEnabled = false
                image_approved.visibility = View.VISIBLE
                layout_certified.alpha = 0.5f
                setImage(bean)
            }
            4 -> {
                btn_submit.text = "提交"
                banEnabled()
                btn_submit.isEnabled = true
                image_approved.visibility = View.GONE
                setImage(bean)

                var message = bean.authRemark
                if (TextUtils.isEmpty(message)) {
                    message = "身份信息审核失败，请重新上传"
                }
                mDialog = CustomDialog.Builder(this@CertifiedActivity)
                        .setMessage(message)
                        .setNegativeButton(R.string.setting_re_upload,
                                R.drawable.button_dialog_green, android.R.color.white) { _, _ ->
                            mDialog!!.dismiss()
                            enabled()
                        }.setPositiveButton(R.string.setting_cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color) { _, _ ->
                            mDialog!!.dismiss()
                            finish()
                        }.create()
                mDialog!!.show()
            }
            else -> {
                btn_submit.text = "提交"
                btn_submit.isEnabled = true
                image_approved.visibility = View.GONE
                enabled()
            }
        }
    }

    private fun banEnabled() {
        img_add_positive.visibility = View.GONE
        img_positive.visibility = View.VISIBLE
        img_add_negative.visibility = View.GONE
        img_negative.visibility = View.VISIBLE
        img_positive.isEnabled = false
        img_add_positive.isEnabled = false
        img_negative.isEnabled = false
        img_add_negative.isEnabled = false
    }

    private fun enabled() {
        img_positive.isEnabled = true
        img_add_positive.isEnabled = true
        img_negative.isEnabled = true
        img_add_negative.isEnabled = true
        img_add_positive.visibility = View.VISIBLE
        img_positive.visibility = View.GONE
        img_add_negative.visibility = View.VISIBLE
        img_negative.visibility = View.GONE
    }

    private fun setImage(bean: UserAutoInfoResp.DataBean) {
        GlideApp.with(this)
                .load(bean.identityObverse)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(R.mipmap.icon_default_picture)
                .into(img_positive)

        GlideApp.with(this)
                .load(bean.identityReverse)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(R.mipmap.icon_default_picture)
                .into(img_negative)
    }

    private fun addListener(bean: UserAutoInfoResp.DataBean) {
        img_add_positive.setOnClickListener {
            requestPermissions("positive", REQUEST_CODE_POSITIVE)
        }
        img_positive.setOnClickListener {
            requestPermissions("positive", REQUEST_CODE_POSITIVE)
        }

        img_add_negative.setOnClickListener {
            requestPermissions("negative", REQUEST_CODE_NEGATIVE)
        }
        img_negative.setOnClickListener {
            requestPermissions("negative", REQUEST_CODE_NEGATIVE)
        }

        btn_submit.setOnClickListener {
            if (!isSelectPositive || !isSelectNegative) {
                ToastUtil.showTip(this@CertifiedActivity, "图片上传不完整")
            } else {
                Timber.e("mFileList$mFileList")
                val positive = mFileList["positive"]
                val negative = mFileList["negative"]
                val userId = RxSPTool.getString(this, USER_ID)
                val id = bean.id
                mPresenter.uploadImage(positive!!.absolutePath, negative!!.absolutePath, userId, id)
            }
        }
    }

    private fun requestPermissions(args: String, requestCode: Int) {
        val rxPermission = RxPermissions(this)
        rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { permission ->
                    when {
                        permission.granted -> {
                            // 用户已经同意该权限
                            Timber.d(permission.name + " is granted.")
                            openBoxing(args, requestCode)
                        }
                        permission.shouldShowRequestPermissionRationale -> {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Timber.d(permission.name + " is denied. More info should be provided.")
                        }
                        else -> {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Timber.d(permission.name + " is denied.")
                        }
                    }
                }
    }

    private fun openBoxing(args: String, requestCode: Int) {
        val cachePath = BoxingFileHelper.getCacheDir(this@CertifiedActivity)
        if (TextUtils.isEmpty(cachePath)) {
            Toast.makeText(applicationContext, R.string.boxing_storage_deny, Toast.LENGTH_SHORT).show()
        } else {
            val destUri = Uri.Builder()
                    .scheme("file")
                    .appendPath(cachePath)
                    .appendPath(String.format(Locale.US, "%s.png", args))
                    .build()
            val singleCropImgConfig = BoxingConfig(BoxingConfig.Mode.SINGLE_IMG)
                    .withCropOption(BoxingCropOption(destUri))
                    .needCamera(R.mipmap.ic_photo_camera_white_24dp).needGif()
                    .withMediaPlaceHolderRes(R.mipmap.icon_default_picture)
            Boxing.of(singleCropImgConfig).withIntent(this@CertifiedActivity, BoxingActivity::class.java).start(this@CertifiedActivity, requestCode)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            data?.let {
                Timber.tag("CertifiedActivity").e("data=$data")
                val medias = Boxing.getResult(data)
                medias?.let {
                    val baseMedia = medias[0] as? ImageMedia ?: return
                    val path = baseMedia.thumbnailPath
                    when (requestCode) {
                        REQUEST_CODE_POSITIVE -> {
                            img_add_positive.visibility = View.GONE
                            img_positive.visibility = View.VISIBLE
                            isSelectPositive = true
                            GlideApp.with(this)
                                    .load(path)
                                    .centerCrop()
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .skipMemoryCache(true)
                                    .placeholder(R.mipmap.icon_default_picture)
                                    .into(img_positive)
                            val files = ArrayList<File>()
                            val file = File(path)
                            files.add(file)
                            withRx(files, "positive")
                        }
                        REQUEST_CODE_NEGATIVE -> {
                            isSelectNegative = true
                            img_add_negative.visibility = View.GONE
                            img_negative.visibility = View.VISIBLE
                            GlideApp.with(this)
                                    .load(path)
                                    .centerCrop()
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .skipMemoryCache(true)
                                    .placeholder(R.mipmap.icon_default_picture)
                                    .into(img_negative)
                            val files = ArrayList<File>()
                            val file = File(path)
                            files.add(file)
                            withRx(files, "negative")
                        }
                        else -> {
                        }
                    }
                }
            }
        }
    }

    companion object {
        private val REQUEST_CODE_POSITIVE = 24
        private val REQUEST_CODE_NEGATIVE = 25
    }

    private fun <T> withRx(photos: List<T>, key: String) {
        mDisposable!!.add(Flowable.just(photos)
                .observeOn(Schedulers.io())
                .map { list ->
                    Luban.with(this).load(list).get()
                }
                //.compose(this.bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { list ->
                    for (file in list) {
                        Timber.i("absolutePath=$file.absolutePath")
                        mFileList[key] = file
                    }
                })
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun uploadImageSuccess(resp: AddUserAutoInfoResp) {
        Timber.e("resp${resp.data}")
        ToastUtil.showTip(this, "身份信息上传成功！！！")
        finish()
    }

    override fun uploadImageFailure(msg: String?) {
        mDialog = CustomDialog.Builder(this@CertifiedActivity)
                .setMessage(msg)
                .setNegativeButton(R.string.setting_re_upload,
                        R.drawable.button_dialog_green, android.R.color.white) { _, _ ->
                    val positive = mFileList["positive"]
                    val negative = mFileList["negative"]
                    val userId = RxSPTool.getString(this, USER_ID)
                    val id = dataBean!!.id
                    mPresenter.uploadImage(positive!!.absolutePath, negative!!.absolutePath, userId, id)
                    mDialog!!.dismiss()
                }.setPositiveButton(R.string.setting_cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create()
        mDialog!!.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDialog?.let {
            mDialog!!.dismiss()
        }
        mDisposable!!.clear()
    }
}
